package com.xjtu.platform.demander.toCsv;

import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.text.csv.CsvWriter;
import cn.hutool.core.util.CharsetUtil;
import com.xjtu.platform.common.Constants;
import com.xjtu.platform.common.Result;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/demander/toCsv")
public class toCsvAPI {

    @Resource
    ToCsvService toCsvService;
    public Result newCsv(String filename){
        csvDto dto = new csvDto();
        dto.setRequest_id(filename);
        List<csvDto> csvDtoList = toCsvService.getCsvDtoList(dto);
        List<String[]> writeLines = new ArrayList<>();
        String[] heads = new String[3];
        heads[0]="Path";
        heads[1]="Answer";
        heads[2]="IsValid";
        writeLines.add(heads);
        for (csvDto dto1:
             csvDtoList) {
            String[] strings =new String[3];
            strings[0] = dto1.getPath();
            strings[1] = dto1.getAns();
            strings[2] = String.valueOf(dto1.getIs_valid());
            writeLines.add(strings);
        }
        write(dto.getRequest_id(),writeLines);
        return Result.success(dto.getRequest_id()+".csv");
    }
    public void write(String filename,List<String[]> writeLine){
        CsvWriter writer = CsvUtil.getWriter(Constants.CSV_ROOT_PATH+filename+".csv",CharsetUtil.CHARSET_GBK);
        writer.write(writeLine);
    }
    @GetMapping("/downLoad/{filename}")
    public void downLoadCsv(@PathVariable String filename,HttpServletResponse response) throws IOException {
        InputStream inputStream = new FileInputStream(Constants.CSV_ROOT_PATH+newCsv(filename).getMessage());
        OutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[10240];//容量为10240字节的缓存区
        int len;//从输入流读取并放入缓存区的数据量
        while((len=inputStream.read(b))!=-1){
            outputStream.write(b,0,len);
        }
        outputStream.flush();
        outputStream.close();
        inputStream.close();
    }

}
